package com.znsd.zl.app.user.controller;

import com.znsd.zl.app.ocr.utils.Base64Util;
import com.znsd.zl.app.user.annotation.Login;
import com.znsd.zl.app.user.service.IAppUserService;
import com.znsd.zl.app.user.vo.req.AppUserBindPhoneReqVO;
import com.znsd.zl.app.user.vo.req.AppUserRealAuthReqVO;
import com.znsd.zl.app.user.vo.req.RecognitionIdCardInfoReqVO;
import com.znsd.zl.utils.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p>
 *      用户实名认证控制器
 * </p>
 *
 * @ClassName AppUserRealNameAuthController
 * @Description TODO
 * @Author jaypdd
 * @Date 2020/9/4 15:10
 * @Version v1.0
 */
@RestController
@RequestMapping("/user")
public class AppUserController {

	@Resource
	private IAppUserService service;

	/**
	 * 上传文件转换成base64字节字符串
	 * @param file  上传的文件对象
	 * @return      返回base64字符串
	 */
	@PostMapping("/upload")
	public R uploadFileToBaseByte(@RequestParam("file") MultipartFile file) {
		try {
			return R.ok().put("file", Base64Util.encode(file.getBytes()));
		} catch (IOException e) {
			e.printStackTrace();
			return R.error("转换失败");
		}
	}

	/**
	 * 用户实名认证
	 * @param reqVO 认证信息请求vo
	 * @return      认证成功 authStatus为true，失败false
	 */
	@PostMapping("/realNameAuth")
	public R userRealNameAuth(@RequestBody AppUserRealAuthReqVO reqVO) {
		try {
			boolean authStatus = service.userRealNameAuth(reqVO);
			return R.ok().put("authStatus", authStatus);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("认证失败，身份信息有误请稍后重试");
		}
	}

	/**
	 * 微信用户绑定手机号
	 * @param reqVO   绑定手机号信息VO
	 * @param request 客户端请求对象
	 * @return        返回绑定状态码，成功true，失败false
	 */
	@PostMapping("/userBindPhone")
	@Login
	public R userBindPhone(@RequestBody AppUserBindPhoneReqVO reqVO, HttpServletRequest request) {
		// 获取用户token
		String token = request.getHeader("token");
		// 传递token解密用户信息
		try{
			boolean bindStatus = service.userBindPhone(reqVO.getEncryptedData(), reqVO.getIv(), token);
			return R.ok().put("bindStatus", bindStatus);
		}catch (Exception ex){
			ex.printStackTrace();
			return R.error("手机号绑定失败，请稍后重试!");
		}
	}

	/**
	 * 获取证件信息
	 * @param reqVO 证件类型，证件加密串
	 * @return      返回识别成功后的证件info
	 */
	@PostMapping("/getIdCardInfo")
	public R getIdCardInfo(@RequestBody RecognitionIdCardInfoReqVO reqVO) {
		return service.recognitionIdCardInfo(reqVO);
	}

}
